package com.wjw.java.oop.polymorphic_;

/**
 * 多态数组：数组的定义类型为父类类型,里面保存的实际元素为子类类型
 */
public class PolymorphicArray {
    public static void main(String[] args) {
        Person [] persons = new Person[5];
        persons[0] = new Person("Person",50);
        persons[1] = new Student("Student1",21,88);
        persons[2] = new Student("Student2",22,99);
        persons[3] = new Teacher("Teacher1",31,5000.99);
        persons[4] = new Teacher("Teacher2",32,6000.88);
        for (int i = 0; i < persons.length; i++) {
            /**
             * 这里的persons[i]编译类型都是Person,运行类型为：Person || Student || Teacher
             * persons[i].say(),会遵循动态绑定机制,即：
             * 当调用对象方法的时候,该方法会和该对象的"内存地址/运行类型"绑定
             */
            String words = persons[i].say();
            System.out.println(words);
            /**
             * 向下转型：强转为子类,然后调用子类特有的方法
             */
            if(persons[i] instanceof Student){
                Student student = (Student) persons[i];
                student.study();
            }else if(persons[i] instanceof Teacher){
                Teacher teacher = (Teacher) persons[i];
                teacher.teach();
            }
        }//for
    }
}
//父类
class Person{
    private String name;
    private int age;
    public String say(){
        return "name:"+this.name+",age:"+this.age;
    }
    //getter、setter...
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return this.age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Person() {
    }
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
//子类
class Student extends Person{
    private double score;//Student类特有属性
    //子类特有方法
    public void study(){
        System.out.println("学生："+super.getName()+"正在学习");
    }
    //重写父类的say()方法
    @Override
    public String say() {
        return super.say()+",score:"+this.score;
    }
    //getter、setter...
    public double getScore() {
        return this.score;
    }
    public void setScore(double score) {
        this.score = score;
    }
    public Student() {
    }
    public Student(String name, int age, double score) {
        super(name, age);
        this.score = score;
    }
}
//子类
class Teacher extends Person{
    private double salary;//Teacher类特有属性
    //子类特有方法
    public void teach(){
        System.out.println("老师："+super.getName()+"正在上课");
    }
    //重写父类的say()方法
    @Override
    public String say() {
        return super.say()+",salary:"+this.salary;
    }
    //getter、setter...
    public double getSalary() {
        return this.salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
    public Teacher() {
    }
    public Teacher(String name, int age, double salary) {
        super(name, age);
        this.salary = salary;
    }
}